package com.youmingxing.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youmingxing.R;
import com.youmingxing.adpter.selfInfo.AuditionRankAdapter;
import com.youmingxing.adpter.selfInfo.AuditionTopRankAdapter;
import com.youmingxing.bean.AuditionDetail;
import com.youmingxing.bean.selfinfo.AuditionRank;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.utils.TimeUtils;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.ExpandableTextView;
import com.youmingxing.view.RefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author evilyin(ChenZhixi)
 * @since 2015-9-9
 *

 */

public class AuditionDetailActivity extends BaseActivity implements View.OnClickListener {

    RefreshListView rankListView;
    View headerView;
    GridView topGridView;
    AuditionRankAdapter adapter;
    List<AuditionRank> auditionRankList = new ArrayList<>();
    int mark = 1;

    ExpandableTextView descText;
    TextView requirementText;
    TextView requirementText2;
    TextView timeText;
    TextView rankTitleText;
    ImageView mainImage;

    int auditionId;
    int movieId;
    int status;
    AuditionDetail detail;
    private ImageView signButton;

    boolean firstLoad = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_audition_detail);
        setTopbarName(R.string.title_activity_audition_detail);
        Bundle bundle = getIntent().getExtras();
        DialogManager.showDialog(this);
        auditionId = bundle.getInt("audition_id");
        movieId = bundle.getInt("movie_id");
        rankListView = (RefreshListView) findViewById(R.id.list_rank);
        mark = 1;
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    void initView() {
        headerView = View.inflate(AuditionDetailActivity.this, R.layout
                .header_audition_detail, null);
        rankListView.addHeaderView(headerView);
        adapter = new AuditionRankAdapter(AuditionDetailActivity.this);
        rankListView.setAdapter(adapter);
        rankListView.setOnLoadMoreListener(new RefreshListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        rankTitleText = (TextView) findViewById(R.id.tv_left);
        findViewById(R.id.layout_more).setVisibility(View.INVISIBLE);
        signButton = (ImageView) findViewById(R.id.audition_sign_up);


        topGridView = (GridView) findViewById(R.id.top_grid_view);
        descText = (ExpandableTextView) findViewById(R.id.expand_text_view);
        requirementText = (TextView) findViewById(R.id.audition_requirement);
        requirementText2 = (TextView) findViewById(R.id.audition_requirement_2);
        timeText = (TextView) findViewById(R.id.audition_time_left);
        mainImage = (ImageView) findViewById(R.id.audition_main_image);

    }

    void updateView() {
        String desc = detail.getIntro().replace("\\n", "\n");
        descText.setText("活动说明:\n" + desc);
        requirementText.setText("类别: " + detail.cate_name + "\n招募人数: " + detail.getQuota());
        requirementText2.setText("性别: " + detail.getGender() + "\n年龄: " + detail.getAge());
        Glide.with(getApplicationContext()).load(detail.cate_bg_img)
                .placeholder(R.drawable.default_16_9).error(R.drawable.default_16_9)
                .crossFade().into(mainImage);
        String timeString = TimeUtils.parseMilliSecond(detail.getBeginOrEndTime() - System
                .currentTimeMillis());
        status = detail.getAuditionStatus();
        switch (status) {
            // 活动状态 1 未开始 2 活动中 3 活动结束未出结果 4 活动结束结果已出
            case 1:
                if (detail.status_tip.isEmpty()) {
                    timeText.setText("距离活动开始还有" + timeString);
                } else {
                    timeText.setText(detail.status_tip);
                }
                rankTitleText.setText("活动尚未开始");
                signButton.setImageResource(R.mipmap.coming);
                signButton.setClickable(false);
                break;
            case 2:
                if (detail.status_tip.isEmpty()) {
                    timeText.setText("距离活动结束还有" + timeString);
                } else {
                    timeText.setText(detail.status_tip);
                }
                rankTitleText.setText("参选选手（目前排名）");
                signButton.setImageResource(R.mipmap.sign_up);
                signButton.setClickable(true);
                signButton.setOnClickListener(AuditionDetailActivity.this);
                break;
            case 3:
                if (detail.status_tip.isEmpty()) {
                    timeText.setText("活动已结束");
                } else {
                    timeText.setText(detail.status_tip);
                }
                rankTitleText.setText("活动已结束（结果确认中）");
                signButton.setImageResource(R.mipmap.over);
                signButton.setClickable(false);
                break;
            case 4:
                if (detail.status_tip.isEmpty()) {
                    timeText.setText("活动结果已公布");
                } else {
                    timeText.setText(detail.status_tip);
                }
                rankTitleText.setText("活动结果已公布");
                signButton.setImageResource(R.mipmap.over);
                signButton.setClickable(false);
                break;
        }


        if (detail.my_apply) {
            signButton.setImageResource(R.mipmap.applyed);
            signButton.setClickable(false);
        }
    }

    @Override
    public void onErrorClick() {
        mark = 1;
        loadData();
    }

    private void loadData() {
        AllStarApi.getAuditionDetail(movieId, auditionId, new BaseJsonHandler(this) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                if (headerView == null) {

                    initView();
                }
                showErrorPage(false);
                JSONObject data = response.optJSONObject("data");
                detail = new AuditionDetail(data);
                updateView();
                if (firstLoad) {
                    AllStarApi.getAuditionRank(movieId, auditionId, mark, jsonHandler);
                    firstLoad = false;
                }
            }

            @Override
            public void onFail(int statusCode, String statusText) {
                super.onFail(statusCode, statusText);
                showErrorPage(true);
            }
        });

    }


    private void loadMore() {
        AllStarApi.getAuditionRank(movieId, auditionId, mark, jsonHandler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.audition_sign_up:
                showDialog("正在验证报名资格");
                AllStarApi.checkQualification(movieId, auditionId, new BaseJsonHandler(AuditionDetailActivity.this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        JSONObject data = response.optJSONObject("data");
                        int result = data.optInt("result");
                        if (result == 1) {
                            Intent intent = new Intent(AuditionDetailActivity.this, InfoConfirmActivity.class);
                            intent.putExtra("movie_id", movieId);
                            intent.putExtra("cate_id", auditionId);
                            intent.putExtra("audition_name", detail.cate_name);
                            startActivity(intent);
                        } else {
                            showToast(data.optString("info"));
                        }
                    }
                });
                break;
        }
    }

    BaseJsonHandler jsonHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            rankListView.endLoadMore();
            JSONArray data = response.optJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                AuditionRank rank = new AuditionRank(data.optJSONObject(i));
                auditionRankList.add(rank);
            }
            if (mark == 1) { //第一页,初始化top4的排名
                if (auditionRankList.size() == 0) {
                    View v = View.inflate(AuditionDetailActivity.this, R.layout.footer_no_data_audition,
                            null);
                    rankListView.noData(v);
                    return;
                } else {
                    if (auditionRankList.size() < 20) {
                        rankListView.noMoreData();
                    }
                    int topLength = auditionRankList.size() > 4 ? 4 : auditionRankList.size();
                    List<AuditionRank> topRank = new ArrayList<>();
                    for (int i = 0; i < topLength; i++) {
                        topRank.add(auditionRankList.get(0));
                        auditionRankList.remove(0);
                    }
                    AuditionTopRankAdapter topRankAdapter = new AuditionTopRankAdapter(AuditionDetailActivity.this, topRank);
                    topGridView.setAdapter(topRankAdapter);
                }
            } else {
                if (data.length() == 0) {
                    rankListView.noMoreData();
                }
            }
            adapter.setAuditionRankList(auditionRankList);
            adapter.notifyDataSetChanged();
            mark++;
        }

        @Override
        public void onFail(int statusCode, String statusText) {
            super.onFail(statusCode, statusText);
            rankListView.endLoadMore();
        }
    };
}
